import time

# print("——————1通用指标（任务完成情况）30%————————")
# step1:通用指标（任务完成情况）30%
# 执行主函数并打印结果
import csv

# OrderedDict([('assignedTo（指派给谁）', 'closed'), ('finishedBy', 'oujiajun'), ('pri', '3'), ('difficulty', 'general'), ('consumed', '8'), ('finishedBy部门', '架构运营事业部'), ('weighted_score', 3.3333333333333335)]) # tasks1 = [
#     {'priority': 'veryImportant', 'difficulty': 1, 'hours': 10,'department': 'A',"score":10},
#     {'priority': 'important', 'difficulty': 2, 'hours': 8,'department': 'A',"score":10},
#     {'priority': 'general', 'difficulty': 3, 'hours': 5,'department': 'A',"score":10},
#     {'priority': 'simple', 'difficulty': 4, 'hours': 3,'department': 'A',"score":10},
#     # ... 可以添加更多任务
# ]


def pre_data(task_, user_task_):
    keys_list=['finishedBy', 'pri', 'difficulty', 'consumed','通用指标-任务完成数']
    new_dict=[]
    for user,u_ in user_task_.items():
        if user in task_:
            dict1 = u_.copy()
            dict2 = task_[user].copy()
            #print('dict2.keys(',list(dict2.keys()))
            dict1.update(dict2)

        else:
            dict1 = u_.copy()
            dict2 = {key: "" for key in keys_list}
            dict1.update(dict2)
            # print("dict1",dict1)
            #print(dict1)
        new_dict.append(dict1)


    return new_dict
def sort_tasks_by_department_score(tasks):
    department_defects = {}
    # for user, department, defects in user_data:
    #     if department not in department_defects:
    #         department_defects[department] = []
    #     department_defects[department].append((user, defects))
    # print(department_defects)
    for dict_u in tasks:
        if dict_u["dept"] not in department_defects:
            department_defects[dict_u["dept"]] = []

        department_defects[dict_u["dept"]].append((dict_u["account"], dict_u["weighted_score"], dict_u["finishedBy"]))

    # Calculate scores and ranks for each department
    user_scores_with_rank = []
    for department, users_defects in department_defects.items():
        # print("department,users_defects:",department,users_defects)
        # Sort the defects list in descending order for each department
        #print("users_defects[weighted_score]",users_defects)

        sorted_defects = sorted(users_defects, key=lambda x: x[1], reverse=True)
        #print("sorted_defects:",sorted_defects)#list
        tem_rank=list(sorted(set([i for _,i,_ in sorted_defects if i!=0 ] ),reverse=True)) #if i!=0
        #print(department,"tem_rank:",tem_rank)
        # Calculate the score and rank for each user in the department
        for i, (user, defects,finished_by) in enumerate(sorted_defects, start=1):
            dict_l = {}
            if defects==0:
                rank=len(tem_rank)+1
            else:
                rank= tem_rank.index(defects)+1
            #print( " (user, defects),rank",(user, defects,finished_by),rank)

            if 2>len(tem_rank)>=1:
                score=100
            elif len(tem_rank)==2:
                if rank==1:
                    score=100
                if rank==2:
                    score=75
            elif len(tem_rank)==3:
                if rank==1:
                    score=100
                if rank==2:
                    score=75
                if rank==3:
                    score=50
            else:
                # Determine the score based on the ranking
                if rank <= len(tem_rank) * 0.25:
                    score = 100
                elif rank <= len(tem_rank) * 0.5:
                    score = 75
                elif rank <= len(tem_rank) * 0.75:
                    score = 50
                else:
                    score = 25
            if defects == 0:
                score = 0
            dict_l["name"]=user
            dict_l["department"] = department
            dict_l["rank"] = rank
            dict_l["score"] = score
            #print("dict_l:",dict_l)
            user_scores_with_rank.append(dict_l)

    for dict_u in tasks:
        for dict_l in user_scores_with_rank:
            if dict_u["account"]==dict_l['name']:
                dict_u["rank"] =  dict_l["rank"]
                dict_u["score"] =  dict_l["score"]
        #print(dict_u)

    return tasks
def evaluate_tasks(tasks):
    tasks_with_scores = calculate_scores_for_tasks(tasks)

    sorted_tasks = sort_tasks_by_department_score(tasks_with_scores)
    return sorted_tasks
def calculate_scores_for_tasks(tasks):
    t_dick=[]
    for task in tasks:
        #print('task"',task)
        task = calculate_weighted_score(task)
        if not task['finishedBy']:
            task['weighted_score']=0
        t_dick.append(task)
    return t_dick
priority_coefficients = {
    "1": 1.5,
    "2": 1.2,
    "3": 1.0,
    "4": 0.9
}

difficulty_coefficients = {
    'veryImportant': 1.5,
    'important': 1.2,
    'general': 1.0,
    'notImportant': 0.9
}

def calculate_weighted_score(task):

    pri_list=task['pri'].split(",")
    difficulty_list=task['difficulty'].split(",")

    hours_score = task['consumed'].split(",")

    score_list=[]
    for num in range(len(pri_list)):
        if not pri_list[num]:
            pri_list[num]="3"
        if not difficulty_list[num]:
            difficulty_list[num]="general"
        if not hours_score[num]:
            hours_score[num]=0

        if pri_list[num] and difficulty_list[num] and hours_score[num]:
            priority_score = priority_coefficients[pri_list[num]]
            difficulty_score = difficulty_coefficients[difficulty_list[num]]
            score_list.append((float(priority_score)*float(difficulty_score)*float(hours_score[num])))
    if score_list:
        score=sum(score_list)
    else:
        score=0
    if task["finishedBy"]==0:
        task["finishedBy"]=None

    task['weighted_score'] = score
    #print(score)
    return task

def user_task_conn(tasks1):
    merged_dict={}
    for task in tasks1:
        # print("task",task)
        if task["finishedBy"] not in merged_dict:
            merged_dict[task["finishedBy"]] = task
            # 任务完成数
            merged_dict[task["finishedBy"]]["通用指标-任务完成数"] = 1
        else:
            for key, values in task.items():

                if key != "finishedBy":

                    # 如果'finishedBy'不在merged_dict中，则创建一个新的列表，并将其作为merged_dict的值
                    merged_dict[task["finishedBy"]][key] = merged_dict[task["finishedBy"]][key] + "," + values
                else:
                    merged_dict[task["finishedBy"]]["通用指标-任务完成数"] += 1
    return merged_dict


# 读取CSV文件
def general_task_done(tasks1, tasks2):
    # 读取CSV文件
    # file1 = open('task.csv', 'r')
    # tasks1 = csv.DictReader(file1)
    # file = open('user.csv', 'r')
    # tasks2 = csv.DictReader(file)
    # t1 = time.time()

    task_ = user_task_conn(tasks1)
    user_task_ = {task['account']: task for task in tasks2}
    # print("user_info_by_realname:",user_info_by_realname)

    tasks1_new = pre_data(task_, user_task_)

    evaluated_tasks = evaluate_tasks(tasks1_new)
    # print(time.time() - t1)
    # for task_i in evaluated_tasks:
    #     print(task_i)
    # print(f"finishedBy: {task_i['finishedBy']},Score: {task_i['score']},finishedBy部门:{task_i['finishedBy部门']}")
    # csv_filename = './通用指标（任务完成情况）30%.csv'
    # with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
    #     fieldnames = evaluated_tasks[0].keys()
    #     writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    #     writer.writeheader()
    #     for user_data in evaluated_tasks:
    #         writer.writerow(user_data)

    return evaluated_tasks
